package com.xiaosu.red_travel.overall;

import com.xiaosu.red_travel.bean.ResultInfo;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class MyExceptionHandler {
    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultInfo exceptionHandler(Exception e, HttpServletRequest req){
        List resuleArr = new ArrayList();
        System.out.println("============================");
        System.out.println(e);
        BindException exception = (BindException) e;
        for (FieldError fieldError : exception.getFieldErrors()) {
            resuleArr.add(fieldError.getDefaultMessage());
        }
        return ResultInfo.no(resuleArr);
    }
}
